from flask import g
from flask_restful import Resource
from flask import request
from flask_restful.reqparse import RequestParser

from toutiao import db
from models.news import Channel, UserChannel, Article
from cache.channel import UserChannelCache
from toutiao.utils.decorators import loginrequired
from cache.channel import UserChannelCache
from toutiao.utils.parsers import check_channel_id


class IndexResource(Resource):

    def get(self):
        """
        获取首页文章列表
        :return:
        """
        # 1. 接收数据验证数据
        parser = RequestParser()
        parser.add_argument("channel_id",location="args",required=True,type=check_channel_id)
        args = parser.parse_args()
        channel_id = args.get("channel_id")
        # 如果频道id是0,在这里给他返回了1,和频道id为1的数据u一样
        if int(channel_id) == 0:
            channel_id = 1
        # 2. 查询数据
        articles = Article.query.filter(Article.channel_id==channel_id,
                                        Article.status==Article.STATUS.APPROVED).all()

        # 3. 对象转字典
        data_list = []
        for item in articles:
            data_list.append({
                "art_id": item.id,
                "title": item.title,
                "aut_id": item.user.id,
                "pubdate": item.ctime.strftime('%Y-%m-%d %H:%M:%S'),
                "aut_name": item.user.name,
                "comm_count": item.comment_count,
                "is_top": False,
                'cover': item.cover,
            })

        # 4.返回相应
        return {'pre_timestamp': 0, 'results': data_list}


# 定义字段
from flask_restful import fields,marshal
all_channel_fields = {
    "id":fields.Integer,
    "name":fields.String
}


class AllChannelResource(Resource):

    method_decorators = {
        'put':[loginrequired]
    }
    """
    获取所有频道
    """

    def get(self):
        # 1. 查询模型,获取对象列表
        # channels = Channel.query.filter(Channel.is_visible==True).order_by(Channel.sequence).all()

        # 2. 将对象列表转换成字典列表,在这里使用了marshal

        # 3. 返回响应 根据返回数据接口,在用envelope包裹一层
        # return marshal(channels,all_channel_fields,envelope="channels")

        from cache.channel import AllChannelCache

        return AllChannelCache.get()


class UserChannelResource(Resource):
    """
    获取用户频道
    """
    def get(self):
        # 1. 先获取用户的信息
        user_id = g.user_id
        if user_id:
            # 2. 如果时登录用户,需要查询登陆用户关注的频道
            # channels = UserChannel.query.filter(UserChannel.user_id==user_id,
            #                                     UserChannel.is_deleted==False).order_by(UserChannel.sequence).all()
            # 登陆用户的名字 UserChannel.channel.name
            data = UserChannelCache(user_id).get()
        else:
            # 3. 如果未登录,需要查询默认的频道
            # channels = Channel.query.filter(Channel.is_default==True,
            #                                 Channel.is_visible==True).order_by(Channel.sequence).all()
            # 未登陆用户的名字 channel.name
            # 未登录的留作作业完成.
            pass
        # 4. 无论登陆还是未登录都有一个推荐
        # data_list = [
        #     {
        #         "id":0,
        #         "name":"推荐"
        #     }
        # ]
        # # 三目运算符格式:item.channel.name（登陆） if 登陆用户 else item.name（未登录的频道）
        # # 对象转字典列表数据
        # for item in channels:
        #     data_list.append({
        #         "id":item.id,
        #         "name":item.channel.name if user_id else item.name
        #     })

        # 返回响应
        return {"channels":data}


    def put(self):
        # 1. 接收数据
        user_channels = request.json.get("channels")

        # 2. 修改数据
        #　把为标记的数据,标记为删除,登录用户只显示推荐的频道
        UserChannel.query.filter(UserChannel.user_id==g.user_id,
                                 UserChannel.is_deleted==False).update({"is_deleted":True})

        # 对前端传递的数据进行遍历
        for channel in user_channels:
            new_data = {
                "is_deleted":False,
                "sequence":channel.get("seq")
            }
            # 对更新的记录进行判断,如果更失败说明没有这条记录,就插入数据
            flag = UserChannel.query.filter(UserChannel.channel_id==channel.get("id"),
                                            UserChannel.user_id==g.user_id).update(new_data)

            # 插入数据
            if flag == 0:
                userchannel = UserChannel()
                userchannel.user_id = g.user_id
                userchannel.channel_id = channel.get('id')
                userchannel.is_deleted = False
                userchannel.sequence = channel.get('seq')
                db.session.add(userchannel)

            # 4. 保存数据
            db.session.commit()

            # 因为修改了频道数据,所以需要清楚缓存
            UserChannelCache(g.user_id).clear()

        # 5. 返回响应
        return {"channels":user_channels},201





